package cn.pzaily.orange.manage.utils;

import cn.pzaily.orange.core.utils.ObjectUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @PackageName: cn.pzaily.youpinxiu.acl.utils
 * @Description:
 * @Author: Pang
 * @Date: 2021-02-22 13:08
 */
public class SecurityUtils {

    /**
     * 获取当前用户
     *
     * @return
     */
    public static UserDetails getUser() {
        Authentication authentication = getAuthentication();
        return getUser(authentication);
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return
     */
    public static UserDetails getUser(Authentication authentication) {
        if (ObjectUtils.isNotNull(authentication)) {
            Object principal = authentication.getPrincipal();
            if (ObjectUtils.isNotNull(principal) && principal instanceof UserDetails) {
                return ((UserDetails) principal);
            }
        }
        return null;
    }

    /**
     * 获取当前用户名称
     *
     * @param
     * @return
     */
    public static String getUsername() {
        Authentication authentication = getAuthentication();
        return getUsername(authentication);
    }

    /**
     * 获取用户名称
     *
     * @param authentication
     * @return
     */
    public static String getUsername(Authentication authentication) {
        UserDetails user = getUser(authentication);
        if (ObjectUtils.isNotNull(user)) {
            return user.getUsername();
        }
        return null;
    }


    /**
     * 获取Authentication 当前登陆信息
     *
     * @return
     */
    public static Authentication getAuthentication() {
        if (ObjectUtils.isNull(SecurityContextHolder.getContext())) {
            return null;
        }
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword    明文密码
     * @param encodePassword 加密密码
     * @return
     */
    public static boolean matchesPassword(String rawPassword, String encodePassword) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder.matches(rawPassword, encodePassword);
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password
     * @return
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        return bCryptPasswordEncoder.encode(password);
    }


}
